<!--
 @description 经销商分店关店-编辑
 @fileName Add.vue
 @author zengqiongying
 @created 2023-04-27 19:31:42
-->
<template>
  <div class="has-foot-pb">
    <Card>
      <DealerCell :detail="dealerData" />
    </Card>
    <Card>
      <FieldSelect
        v-model="formData.isOtherReceiveManagerKnow"
        title="是否需要其他业务客户经理接收知晓"
        :url="`/data-dict/app/v2/dictionary/BOOLEANS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        required
      />
      <template v-if="[1, '1'].includes(formData.isOtherReceiveManagerKnow)">
        <Cell
          v-if="dealerData.officeCode && detail.customerCode"
          :modelValue="formData.receiveManagerName"
          title="接收客户经理"
          placeholder="选择客户经理"
          :required="['1', 1].includes(formData.isOtherReceiveManagerKnow)"
          @right="onSearchCustomerManager"
        />

        <template v-if="!!formData.receiveManagerCode">
          <Cell :modelValue="formData.receiveManagerCode" title="接收客户经理编码" readonly />
          <Cell :modelValue="formData.receiveManagerTypeName" title="接收客户经理类型" readonly />
          <Cell :modelValue="formData.receiveManagerTel" title="接收客户经理电话" readonly />
        </template>
      </template>
      <Cell title="提报意见" is-column custom :right="false">
        <qmp-field v-model="formData.submitAnOpinion" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>

    <Card title="选择关店店铺" sub-title="点击编辑进入编辑店铺">
      <div class="shop-list">
        <div class="shop-checkbox" v-for="(item, i) in shopList" :key="i">
          <div class="check-status" :class="{ checked: [1, '1'].includes(item.isChange) }"></div>
          <div class="shop-item has-pr">
            <div class="title">{{ item.name }}</div>
            <div class="address">{{ item.shopAddr }}</div>
            <div class="btn-edit" @click.stop="onEditShop(item)"></div>
          </div>
        </div>
      </div>
    </Card>

    <Card title="门店建设信息" v-if="shopConstructDTOS.length">
      <ShopItem :list="shopConstructDTOS" :dictData="dictData" :readonly="false" />
    </Card>

    <Card title="销售转让信息">
      <Cell title="是否涉及销量转让" custom :right="false" required>
        <qmp-switch
          v-model="formData.isTransferSales"
          :disabled="disabledTransferSales"
          :active-value="1"
          :inactive-value="0"
        >
          <template #background>
            <span class="qmp-switch__background">
              {{ [1, '1'].includes(formData.isTransferSales) ? '涉及' : '不涉及' }}</span
            >
          </template>
        </qmp-switch>
      </Cell>
      <Cell
        title="关系证明附件"
        is-column
        custom
        :required="[1, '1'].includes(formData.isTransferSales)"
        :right="false"
      >
        <AttachmentUpload v-model="attachment.ACCESS071" type-code="ACCESS071" :objectId="id" />
      </Cell>
      <Cell
        title="交接双方现场签订照片"
        is-column
        custom
        :required="[1, '1'].includes(formData.isTransferSales)"
        :right="false"
      >
        <AttachmentUpload v-model="attachment.ACCESS111" type-code="ACCESS111" :objectId="detail.id" />
      </Cell>
      <Cell v-if="Object.keys(detail).length > 0" title="交接双方现场签订照片模板下载" is-column custom readonly>
        <AttachmentUpload v-if="templateFileList.ACCESS111.length" v-model="templateFileList.ACCESS111" readonly />
        <div v-else>暂无文件</div>
      </Cell>
    </Card>

    <div class="ctm-content-foot">
      <div class="btn radius-larg ctm-btn-warning" @click="onSave('B')">提交</div>
      <div class="btn radius-larg ctm-btn-main" @click="onView">预览</div>
      <div class="btn radius-larg ctm-btn-main" @click="onSave('A')">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick, computed, watch } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import DealerCell from '@/components/DealerCell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import AttachmentUpload from '@/components/AttachmentUpload/index.vue'
  import { detail, saveOrSubmit } from '@/apis/dealerMarketing/ShutUpShop'
  import { initFormData } from '@/utils'
  import { getDictList } from '@/apis/dataDict'
  import { getAttachmentTemplate, queryAttachmentList } from '@/apis/common'
  import ShopItem from './components/ShopItem.vue'

  const none: any[] = [undefined, null, '']
  interface anyObjectModle {
    [key: string]: any
  }
  export default {
    name: 'DealerShutUpShopEdit',
    components: { Card, Cell, DealerCell, FieldSelect, AttachmentUpload, ShopItem },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const $route = useRoute()
      const datas = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        dictData: {
          BELONG_STAGE: [],
          BOOLEANS: [],
          CTM_SHOP_CONS_DATA_PROCESS_TYPE: []
        },
        detail: {},
        formData: {
          code: '', //单据编号
          isOtherReceiveManagerKnow: '',
          receiveManagerCode: '', // 接收客户经理
          receiveManagerName: '',
          receiveManagerTel: '',
          receiveManagerTypeCode: '',
          receiveManagerTypeName: '',
          submitAnOpinion: '',
          isTransferSales: 0 //是否涉及销售转让
        },
        attachment: {
          ACCESS071: [], // 关系证明附件
          ACCESS111: [] //交接现场签订照片
        },
        templateFileList: {
          ACCESS111: [] //交接双方现场签订照片模板下载
        },
        allShopConstructList: [
          /* {
            shopName:'店名',
            belongStage:'所处阶段',
            handleType:'处理方式'
          } */
        ], //所有门店建设
        shopConstructDTOS: [] // 当前所选门店的门店建设数据
      })

      onBeforeRouteLeave((to, from) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['DealerInfoShutUpShop', 'DealerShutUpShopDetail'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
      })
      const dealerData = computed(() => {
        const d = { ...datas.detail }
        return {
          code: d.customerCode || '',
          name: d.customerName || '',
          officeCode: d.officeCode || '',
          officeName: d.officeName || '',
          createBy: d.createBy || ''
        }
      })
      const shopList = computed(() => {
        return datas.detail?.shopBusinessDTOS || []
      })
      const disabledTransferSales = computed(() => {
        // 禁止修改“是否涉及销量转让”：当所有分店“是否交接”值为否时，“是否转让销量”值默认为否，不可编辑，关系证明附件不必填
        if (shopList.value.length === 0) return true
        return shopList.value.every((v: any) => ![1, '1'].includes(v.isMarketConnect))
      })
      const selectedShopsCode = computed(() => {
        // 当前所选门店
        const selectedShops = shopList.value.filter((v: any) => [1, '1'].includes(v.isChange))
        if (selectedShops.length == 0) {
          return []
        }
        return selectedShops.map((v: any) => v.code)
      })

      watch(
        () => disabledTransferSales.value,
        (val) => {
          if (!val) {
            datas.formData.isTransferSales = 0
          }
        }
      )

      const initDictData = async () => {
        const BELONG_STAGE = await getDictList('BELONG_STAGE')
        const BOOLEANS = await getDictList('BOOLEANS')
        const CTM_SHOP_CONS_DATA_PROCESS_TYPE = await getDictList('CTM_SHOP_CONS_DATA_PROCESS_TYPE')
        datas.dictData.BELONG_STAGE = BELONG_STAGE || []
        datas.dictData.BOOLEANS = BOOLEANS || []
        datas.dictData.CTM_SHOP_CONS_DATA_PROCESS_TYPE = CTM_SHOP_CONS_DATA_PROCESS_TYPE || []
      }

      const getFormData = () => {
        const { formData, shopConstructDTOS, attachment }: any = datas
        let data: anyObjectModle = {
          ...formData
        }
        data.isTransferSales = [1, '1'].includes(formData.isTransferSales) ? 1 : 0

        if (shopConstructDTOS.length > 0) {
          data.shopConstructDTOS = shopConstructDTOS
        }
        let attachmentDTOS: any = []
        Object.keys(attachment).forEach((key: any) => {
          const attrList = attachment[key].map((v: any) => {
            return {
              ...v,
              ...{ modelId: data.id }
            }
          })
          attachmentDTOS = [...attachmentDTOS, ...attrList]
        })
        data.attachmentDTOS = attachmentDTOS
        return data
      }

      const onSave = (schedule: string, callback: any) => {
        const data: anyObjectModle = getFormData()
        if (schedule === 'B') {
          if (none.includes(data.isOtherReceiveManagerKnow)) {
            proxy.$toast('请选择是否需要其他业务客户经理接收知晓')
            return
          }
          if ([1, '1'].includes(data.isOtherReceiveManagerKnow)) {
            if (none.includes(data.receiveManagerCode)) {
              proxy.$toast('请选择接收客户经理')
              return
            }
          }
          const flag = shopList.value.some((v: any) => [1, '1'].includes(v.isChange))
          if (!flag) {
            proxy.$toast('选择关店店铺')
            return
          }

          if (data.shopConstructDTOS && data.shopConstructDTOS.length > 0) {
            // 判断门店建设处理方式是否选择
            const flag = data.shopConstructDTOS.some((v: any) => {
              return none.includes(v.handleType)
            })
            if (flag) {
              proxy.$toast('请完善门店建设信息数据处理方式')
              return
            }
          }

          if (data.isTransferSales === 1) {
            const { attachment } = datas
            if (!attachment.ACCESS071 || attachment.ACCESS071.length === 0) {
              proxy.$toast('请上传关系证明附件')
              return
            }
            if (!attachment.ACCESS111 || attachment.ACCESS111.length === 0) {
              proxy.$toast('请上传交接双方现场签订照片')
              return
            }
          }
        }

        data.schedule = schedule
        data.id = datas.id
        saveOrSubmit(data).then((res: any) => {
          if (res.success === 1) {
            proxy.$toast(schedule === 'B' ? '提交成功' : '保存成功')
            proxy.$SimpleEvents.emit('refreshCustomerChangeItem', data.id)
            if (callback) {
              callback()
              return
            }
            nextTick(() => {
              $router.goBack()
            })
          }
        })
      }
      const onView = () => {
        onSave('A', () => {
          $router.push({
            path: '/dealerShutUpShop/preview',
            query: {
              id: `${datas.id}`
            }
          })
        })
      }

      const onChangeReceiveManager = (d: any) => {
        const receiveManager = {
          receiveManagerCode: d?.personCode || '',
          receiveManagerName: d?.personName || '',
          receiveManagerTel: d?.personTel || '',
          receiveManagerTypeCode: d?.accountType || '',
          receiveManagerTypeName: d?.accountTypeName || ''
        }
        datas.formData = { ...datas.formData, ...receiveManager }
      }

      const onSearchCustomerManager = () => {
        const officeCode = dealerData.value.officeCode
        const customerCode = datas.detail.customerCode
        if ([undefined, null, ''].includes(officeCode)) {
          proxy.$toast('请先选择办事处')
          return
        }
        proxy.$SimpleEvents.registerEvent('ShutUpShopSetManager', (data: any) => {
          onChangeReceiveManager(data)
        })
        $router.push({
          path: '/search/customerManager',
          query: {
            name: 'ShutUpShopSetManager',
            office: officeCode,
            customer: customerCode
          }
        })
      }
      const getDetail = () => {
        const id = `${datas.id}`
        detail(id).then((res) => {
          const d = res.data

          datas.detail = d
          initFormData(d, datas.formData)
          datas.formData.isTransferSales = [1, '1'].includes(d.isTransferSales) ? 1 : 0

          datas.allShopConstructList = d.shopConstructDTOS || []
        })
      }
      const onEditShop = (data: any) => {
        proxy.$SimpleEvents.registerEvent('ShutUpShopUpdateShopInfo', (newData: any) => {
          detail(datas.id).then((res) => {
            datas.detail = { ...datas.detail, ...res.data }
          })
        })

        localStorage.setItem('shutShopInfo', JSON.stringify({ ...data, ...{ changeCode: datas.detail.code } }))
        $router.push({
          path: '/dealerShutUpShop/editShop'
        })
      }

      const getShopConstructList = () => {
        // 门店建设信息：取当前所选店铺所对应的门店建设信息
        if (selectedShopsCode.value.length === 0 || datas.allShopConstructList.length === 0) {
          datas.shopConstructDTOS = []
        }
        datas.shopConstructDTOS = datas.allShopConstructList.filter((v: any) => {
          return selectedShopsCode.value.includes(v.shopCode)
        })
      }
      const downTemplate = async () => {
        const codes = ['ACCESS111'] // 需下载模板的附件类型编码
        codes.forEach(async (code) => {
          const configId = await getAttachmentTemplate(code)
          if (configId) {
            const data = await queryAttachmentList(configId)
            datas.templateFileList[code] = data
          }
        })
      }

      watch(
        () => selectedShopsCode.value,
        () => {
          getShopConstructList()
        },
        {
          immediate: true,
          deep: true
        }
      )

      downTemplate()
      initDictData()
      getDetail()
      return {
        ...toRefs(datas),
        dealerData,
        shopList,
        disabledTransferSales,
        selectedShopsCode,
        getShopConstructList,
        onView,
        onSave,
        onSearchCustomerManager,
        onEditShop
      }
    }
  }
</script>
<style lang="less" scoped>
  .shop-list {
    padding: 0 16px;
    /deep/ .qmp-checkbox__label {
      flex: 1;
    }
    .shop-checkbox {
      display: flex;
      align-items: center;
      overflow: hidden;
      user-select: none;
      .check-status {
        margin-right: 16px;
        width: 24px;
        height: 24px;
        background-repeat: no-repeat;
        background-size: 24px 24px;
        background-image: url(~@/assets/images/checkbox.png);
        &.checked {
          background-image: url(~@/assets/images/checkbox-check.png);
        }
      }
    }
    .shop-item {
      flex: 1;
      padding: 16px 0;
      position: relative;
      &.has-pr {
        padding-right: 56px;
      }
      .title {
        margin-bottom: 2px;
        font: var(--font-main-title-strengthen);
        color: var(--texticon-default-strong);
      }
      .address {
        font: var(--font-main-title-body);
        color: var(--texticon-default-strong);
      }
      .btn-edit {
        position: absolute;
        z-index: 9;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 24px;
        height: 24px;
        background-image: url(~@/assets/images/edit-line.png);
        background-size: 24px 24px;
        background-repeat: no-repeat;
      }
    }
  }
</style>
